package org.kim.command;

import org.kim.core.Session;
import org.kim.exception.ServiceException;
import org.kim.pojo.Account;

import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;

public class BookCommandProxy {

    private Class clz;
    private BookCommand bookCommand;

    public BookCommandProxy() throws InstantiationException, IllegalAccessException {
        clz = BookCommand.class;
        bookCommand = (BookCommand) clz.newInstance();
    }

    public String action(String actionType, String[] commandStrs) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, ServiceException {

        Method method = clz.getMethod(actionType, String[].class);
        Annotation[] annotations = method.getAnnotations();
        boolean canAction = false;
        List<Account> loginAccountList = null;
        for (Annotation annotation : annotations) {
            if (annotation.annotationType().equals(Login.class) && ((Login) annotation).required()) {
                loginAccountList = Session.getAll();
                if (loginAccountList != null && loginAccountList.size() > 0) {
                    canAction = true;
                } else {
                    //throw new ServiceException("please login firstly");
                    System.out.println("Please login firstly");
                }
            }
            if (annotation.annotationType().equals(Permission.class)) {
                String requiredRole = ((Permission) annotation).role();
                String loginAccountRole = loginAccountList.get(0).getRole();
                if (requiredRole.equals(loginAccountRole)) {
                    canAction = true;
                } else {
                    canAction = false;
                    //throw new ServiceException("permission insufficient");
                    System.out.println("Permission insufficient");
                }
            }
        }
        if (canAction) {
            return (String) method.invoke(bookCommand, (Object)commandStrs);
        }
        return "";
    }
}
